package com.woniuxy.dr_mall.controller;


import com.woniuxy.dr_mall.entity.DrFavoriteView;
import com.woniuxy.dr_mall.entity.DrUser;
import com.woniuxy.dr_mall.entity.MyResponseEntity;
import com.woniuxy.dr_mall.global.ResponseStateCode;
import com.woniuxy.dr_mall.service.IDrUserService;
import com.woniuxy.dr_mall.utils.Audience;
import com.woniuxy.dr_mall.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 张哲轩
 * @since 2021-08-11
 */
@Slf4j
@RestController
@RequestMapping("/dr_mall/drUser")
public class DrUserController {
    @Autowired
    private IDrUserService iDrUserService;

    @Autowired
    private Audience audience;

    @PostMapping("editpwd")
    public MyResponseEntity editpwd(@RequestBody DrUser drUser,@RequestHeader("token") String token) {
        int id= JwtUtil.getId(token,audience.getBase64Secret());

        DrUser user = iDrUserService.getById(id);
        //DrUser user = iDrUserService.getById(drUser.getId());
        if (drUser.getPassword().equals(user.getPassword())) {
            iDrUserService.editPasswordById(id, drUser.getNewPassword());
            return MyResponseEntity.SUCCESS;
        }
        return MyResponseEntity.PASSWORD_ERROR;

    }

    @PostMapping("send_email")
    public MyResponseEntity<?> validEmail(String email) {
        return iDrUserService.getValidateCode(email);
    }

    @PostMapping("register")
    public MyResponseEntity<?> register(String account, String password, String vCode) {
        return iDrUserService.register(account, password, vCode);
    }

    @PostMapping("back_end-login")
    public MyResponseEntity<?> login(@RequestBody DrUser user) {
        UsernamePasswordToken token = new UsernamePasswordToken(user.getAccount(), user.getPassword());
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
        } catch (UnknownAccountException e) {
            return new MyResponseEntity<String>(ResponseStateCode.ACCOUNT_NOT_FOUND, "账户不存在");
        } catch (IncorrectCredentialsException e) {
            subject.getSession().removeAttribute("user");
            return new MyResponseEntity<String>(ResponseStateCode.PASSWORD_ERROR, "密码错误");
        }
        return MyResponseEntity.SUCCESS;

    }

    @PostMapping("login")
    public MyResponseEntity<?> login(@RequestBody DrUser user, HttpServletResponse response) {
        UsernamePasswordToken token = new UsernamePasswordToken(user.getAccount(), user.getPassword());
        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
            //产生jwt
            String jwtToken = JwtUtil.createJWT(iDrUserService.getByAccount(user.getAccount()).getId(), user.getAccount(), audience);
            response.addHeader("token", jwtToken);
        } catch (AuthenticationException e) {
            if (e instanceof UnknownAccountException) {
                return new MyResponseEntity<String>(ResponseStateCode.ACCOUNT_NOT_FOUND, "账户不存在");
            } else if (e instanceof IncorrectCredentialsException) {
                //密码验证失败移除session
                subject.getSession().removeAttribute("user");
                return new MyResponseEntity<String>(ResponseStateCode.PASSWORD_ERROR, "密码错误");
            }
        }
        return MyResponseEntity.SUCCESS;
    }

    /**
     * 通过id查询用户的信息
     *
     * @return
     */
    @GetMapping("maintain")
    public MyResponseEntity selectImformationById(@RequestHeader("token") String token){
        int userId = JwtUtil.getId(token, audience.getBase64Secret());
        System.out.println(userId);
        DrUser drUser = iDrUserService.selectImformationById(userId);
        return new MyResponseEntity<DrUser>(drUser);
    }

    /**
     * 通过id修改用户的信息
     *
     * @param user
     * @return
     */
    @PostMapping("updateUserImformation")
    public MyResponseEntity<DrUser> updateUserImformation(@RequestBody DrUser user) {
        System.out.println(user);
        iDrUserService.useIdUpdateImformation(user);
        return new MyResponseEntity<>(200, "ok");
    }

    /**
     * 通过用户id查询用户的收藏信息
     *
     * @param
     * @return
     */
    @GetMapping("selectUserFavoriteImformation")
    public MyResponseEntity<?> selectUserFavoriteImformation(@RequestHeader("token") String token) {
        int userId = JwtUtil.getId(token, audience.getBase64Secret());
        System.out.println(userId);
        List<DrFavoriteView> userFavorite = iDrUserService.selectUserFavoriteById(userId);
        System.out.println(userFavorite);
        for (DrFavoriteView drFavoriteView : userFavorite) {
            String path = drFavoriteView.getPicture().getImage();
            drFavoriteView.getPicture().setImage("http://192.168.6.100:8080/"+path);
        }
        MyResponseEntity<List<DrFavoriteView>> myResponseEntity = new MyResponseEntity<>();
        myResponseEntity.setData(userFavorite);
        myResponseEntity.setCode(200);
        myResponseEntity.setMsg("ok");
        return myResponseEntity;
    }


    @GetMapping("list")
    public MyResponseEntity<List<DrUser>> getUsers() {
//        log.debug("current:{}",current);
//        if (current==null){
//            current=1;
//        }
//        //封装了分页查询的相关的属性
//        Page<DrUser> page = new Page<>(current, 4);
//        //封装了查询条件
//        QueryWrapper<DrUser> queryWrapper = new QueryWrapper<>();
//        //判断前台是否模糊查询名字
//        if (user.getName() != null && user.getName().trim().length() != 0) {
//            queryWrapper.like("name", user.getName());
//        }
//        //判断前台是否传了账号
//        if (user.getAccount() != null && user.getAccount().trim().length() != 0) {
//            queryWrapper.ge("account", user.getAccount());
//        }
//        //判断前台是否传了密码
//        if (user.getPassword() != null && user.getPassword().trim().length() != 0) {
//            queryWrapper.ge("password", user.getPassword());
//        }
//        //判读状态是否正常
//        if (user.getStatus() != null) {
//            queryWrapper.eq("status", "y");
//        }
//        Page<DrUser> userPage = iDrUserService.page(page, queryWrapper);
//        //计算出总页数
//        int totalPage = (int) (userPage.getTotal() % userPage.getSize()==0?userPage.getTotal() / userPage.getSize():userPage.getTotal() / userPage.getSize()+1);
//        //定义要遍历的页码数组
//        int[] pages=new int[totalPage];
//        for (int i=1;i<=totalPage;i++){
//            pages[i-1]=i;
//        }
//        log.debug("pages:{}",pages);
        return new MyResponseEntity<>(iDrUserService.getUsers());
    }

    @GetMapping("enable")
    public MyResponseEntity<?> getNormal(int id) {
        iDrUserService.getNormal(id);
        return MyResponseEntity.SUCCESS;
    }

    @GetMapping("disable")
    public MyResponseEntity<?> getUnNormal(int id) {
        iDrUserService.getUnNormal(id);
        return MyResponseEntity.SUCCESS;
    }

    @GetMapping("getInfo")
    public MyResponseEntity getInfo(@RequestHeader("token") String token){
        int id= JwtUtil.getId(token,audience.getBase64Secret());
        DrUser user = iDrUserService.getById(id);

        MyResponseEntity myResponseEntity = new MyResponseEntity();
        myResponseEntity.setCode(ResponseStateCode.SUCCESS);
        myResponseEntity.setData(user);
        return myResponseEntity;
    }
}

